using System;
using Project.ViewModels;
using Project.Views.Abstractions;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Project.Views
{
    [RequireComponent(typeof(CanvasGroup), typeof(LayoutElement))]
    public class ItemUIView : MonoUIViewBase<ItemViewModel>, IBeginDragHandler, IDragHandler, IEndDragHandler, IDisposable
    {
        private Transform _startingParent;
        private Vector3 _startingPosition;
        private int _startingSiblingIndex;

        [SerializeField] private CanvasGroup _canvasGroup;
        [SerializeField] private LayoutElement _layoutElement;
        [SerializeField] private Image _itemImage;
        [SerializeField] private TMP_Text _quantityOfItemsText;

        public void OnBeginDrag(PointerEventData eventData)
        {
            _startingParent = this.transform.parent;
            _startingSiblingIndex = this.transform.GetSiblingIndex();
            _startingPosition = this.transform.position;

            _canvasGroup.blocksRaycasts = false;
            _layoutElement.ignoreLayout = true;

            this.transform.SetParent(RootUIView.transform);

            ViewModel.IsDragging.Value = true;
        }
        public void OnDrag(PointerEventData eventData)
        {
            this.transform.Translate(eventData.delta);
        }
        public void OnEndDrag(PointerEventData eventData)
        {
            _canvasGroup.blocksRaycasts = true;
            _layoutElement.ignoreLayout = false;

            this.transform.SetParent(_startingParent);
            this.transform.SetSiblingIndex(_startingSiblingIndex);
            this.transform.position = _startingPosition;

            ViewModel.IsDragging.Value = false;
        }

        public void Dispose()
        {
            ViewModel.Sprite.ValueChanged -= OnItemSpriteValueChanged;
            ViewModel.QuantityText.ValueChanged -= OnQuantityOfItemsTextValueChanged;
        }

        protected override void OnAfterInitialization()
        {
            OnItemSpriteValueChanged(ViewModel.Sprite.Value);
            OnQuantityOfItemsTextValueChanged(ViewModel.QuantityText.Value);

            ViewModel.Sprite.ValueChanged += OnItemSpriteValueChanged;
            ViewModel.QuantityText.ValueChanged += OnQuantityOfItemsTextValueChanged;
        }

        private void OnItemSpriteValueChanged(Sprite newValue)
        {
            _itemImage.sprite = newValue;

            var isEmpty = newValue == null;

            _canvasGroup.alpha = isEmpty ? 0 : 1;
            _canvasGroup.blocksRaycasts = !isEmpty;
        }
        private void OnQuantityOfItemsTextValueChanged(string newValue) => 
            _quantityOfItemsText.text = newValue;
    }
}
